// pages/schedule/schedule.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentDate: new Date().toISOString().split('T')[0],
    events: [
      {
        id: 1,
        title: '团队会议',
        date: '2024-03-15',
        time: '10:00',
        type: 'work',
        description: '讨论项目进度和下一步计划',
        isCompleted: false,
        points: 10
      },
      {
        id: 2,
        title: '健身',
        date: '2024-03-15',
        time: '18:30',
        type: 'personal',
        description: '跑步5公里',
        isCompleted: true,
        points: 5
      },
      {
        id: 3,
        title: '阅读',
        date: '2024-03-16',
        time: '21:00',
        type: 'personal',
        description: '阅读《原子习惯》一小时',
        isCompleted: false,
        points: 3
      }
    ],
    showAddDialog: false,
    eventForm: {
      id: 0,
      title: '',
      date: '',
      time: '',
      type: 'work',
      description: '',
      isCompleted: false,
      points: 5
    },
    isEdit: false,
    typeOptions: [
      { label: '工作', value: 'work' },
      { label: '个人', value: 'personal' },
      { label: '重要', value: 'important' },
      { label: '其他', value: 'other' }
    ],
    pointsOptions: [1, 2, 3, 5, 8, 10, 15, 20],
    totalPoints: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.calculateTotalPoints();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  formatDate(date, format = 'normal') {
    if (!date) return ''
    
    const d = new Date(date)
    const year = d.getFullYear()
    const month = d.getMonth() + 1
    const day = d.getDate()
    
    if (format === 'display') {
      return `${year}年${month}月${day}日`
    }
    
    return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
  },
  
  hasEvents(day) {
    return this.data.events.some(event => 
      this.formatDate(event.date) === day
    )
  },
  
  showAddEventDialog() {
    const today = new Date().toISOString().split('T')[0];
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    
    this.setData({
      showAddDialog: true,
      isEdit: false,
      eventForm: {
        id: Date.now(),
        title: '',
        date: today,
        time: `${hours}:${minutes}`,
        type: 'work',
        description: '',
        isCompleted: false,
        points: 5
      }
    })
  },

  closeDialog() {
    this.setData({
      showAddDialog: false
    })
  },

  onInputChange(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`eventForm.${field}`]: value
    });
  },

  onTypeChange(e) {
    this.setData({
      'eventForm.type': e.detail.value
    });
  },

  onPointsChange(e) {
    this.setData({
      'eventForm.points': parseInt(e.detail.value)
    });
  },

  saveEvent() {
    const form = this.data.eventForm;
    
    if (!form.title || !form.date || !form.time) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }
    
    const events = this.data.events;
    
    if (this.data.isEdit) {
      const index = events.findIndex(e => e.id === form.id);
      if (index !== -1) {
        events[index] = {...form};
      }
    } else {
      events.push({...form});
    }
    
    this.setData({ 
      events,
      showAddDialog: false 
    });
    
    wx.showToast({
      title: this.data.isEdit ? '修改成功' : '添加成功',
      icon: 'success'
    });
    
    this.calculateTotalPoints();
  },

  editEvent(e) {
    const id = e.currentTarget.dataset.id;
    const event = this.data.events.find(ev => ev.id === id);
    
    if (event) {
      this.setData({
        isEdit: true,
        showAddDialog: true,
        eventForm: {...event}
      });
    }
  },

  deleteEvent(e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这个日程吗？',
      success: res => {
        if (res.confirm) {
          const events = this.data.events.filter(ev => ev.id !== id);
          this.setData({ events });
          this.calculateTotalPoints();
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  toggleComplete(e) {
    const id = e.currentTarget.dataset.id;
    const events = this.data.events;
    const index = events.findIndex(ev => ev.id === id);
    
    if (index !== -1) {
      events[index].isCompleted = !events[index].isCompleted;
      
      this.setData({ events });
      this.calculateTotalPoints();
      
      if (events[index].isCompleted) {
        wx.showToast({
          title: `+${events[index].points}积分`,
          icon: 'success'
        });
        
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/points/points'
          });
        }, 1500);
      }
    }
  },

  calculateTotalPoints() {
    const total = this.data.events
      .filter(ev => ev.isCompleted)
      .reduce((sum, ev) => sum + ev.points, 0);
    
    this.setData({ totalPoints: total });
    
    const app = getApp();
    app.globalData = app.globalData || {};
    app.globalData.points = total;
  },

  getCurrentDateEvents() {
    return this.data.events.filter(ev => ev.date === this.data.currentDate);
  },

  goToPoints() {
    wx.navigateTo({
      url: '/pages/points/points'
    });
  },

  changeDate(e) {
    this.setData({
      currentDate: e.detail.value
    });
  }
})